package com.atguigu.demo.servlet;

import com.alibaba.fastjson.JSON;
import com.atguigu.demo.entity.Result;
import com.atguigu.demo.entity.Tiger;
import com.atguigu.demo.service.api.TigerService;
import com.atguigu.demo.service.impl.TigerServiceImpl;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;

import java.io.IOException;

@WebServlet(name = "TigerServletSave", value = "/TigerServletSave")
public class TigerServletSave extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // ※补充功能：获取自定义请求消息头
        String atguigu = request.getHeader("atguigu");
        System.out.println("atguigu = " + atguigu);

        TigerService tigerService = new TigerServiceImpl();

        // 1、从请求参数中获取 Tiger 对象相关数据
        String tigerName = request.getParameter("tigerName");
        String tigerAge = request.getParameter("tigerAge");
        String tigerSalary = request.getParameter("tigerSalary");

        // 2、把请求参数数据封装到 Tiger 对象中
        Tiger tiger = new Tiger(null, tigerName, Integer.parseInt(tigerAge), Double.parseDouble(tigerSalary));

        // 3、调用 Service 方法执行保存
        tigerService.saveTiger(tiger);

        // 4、返回响应
        response.getWriter().write(JSON.toJSONString(Result.ok()));
    }
}
